<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工艺编码" prop="tecCode">
        <el-input v-model="queryParams.tecCode" placeholder="请输入工艺编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['mes:tec:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['mes:tec:edit']">修改</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mes:tec:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['mes:tec:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tecList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="工艺编码" align="center" prop="tecCode" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:tec:edit']">修改</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['mes:tec:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />


    <!-- 添加或修改产品工艺对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工艺编码" prop="tecCode">
          <el-input :disabled="nomodify" v-model="form.tecCode" placeholder="请输入工艺编码" />
        </el-form-item>
        <el-form-item label="绑定产品" prop="proId">
          <!-- <el-input v-model="form.proId" placeholder="请输入工艺编码" /> -->
          <el-select :disabled="nomodify" v-model="form.proId" filterable placeholder="请选择">
            <el-option v-for="item in proOptions" :key="item.id" :label="item.proName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <el-divider content-position="left">工序列表</el-divider>
      <label>选择工序: </label>
      <el-select v-model="chooseProce" filterable placeholder="请选择" @change="proceChange">
        <el-option v-for="item in proceOptions" :key="item.id" :label="item.proceName" :value="item.id">
        </el-option>
      </el-select>

      <draggable :list="form.proceInfos">
        <transition-group>
          <el-card
            style="position: relative;border-radius: 15px;margin-bottom: 5px;margin-top: 5px;background-image: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);"
            shadow="always" v-for="(item, index) in form.proceInfos" :key="item.id">
            <div style="display: inline-block;">
              <label style="display: block;">工序顺序：{{ index }}</label>
              <label style="display: block;">工序名称：{{ item.proceName }}</label>
            </div>
            <div style="display: inline-block;height: 100%;">
              <div
                style="display: flex;text-align: center;position: absolute;right: 180px;top: 0; height: 100%;width: 80px;align-items: center;justify-content: center;">
                <button id="shebeibtn" @click="proMtrSet(index)">原料设置</button>
              </div>
              <div
                style="display: flex;text-align: center;position: absolute;right: 100px;top: 0; height: 100%;width: 80px;align-items: center;justify-content: center;">
                <button id="shebeibtn" @click="proDeviceSet(index)">设备设置</button>
              </div>
            </div>
            <div
              style="display: flex;text-align: center;position: absolute;right: 0;top: 0; height: 100%;width: 80px;align-items: center;justify-content: center;">
              <el-button id="daohuobtn" type="danger" icon="el-icon-delete" circle @click="proceDel(index)"></el-button>
            </div>
          </el-card>
        </transition-group>
      </draggable>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 工序原料设置对话框 -->
    <transition name="el-fade-in">


      <el-dialog title="工序原料设置" :visible.sync="proMtrSetOpen" v-if="proMtrSetOpen" width="500px" append-to-body>
        <label>选择物料</label>
        <el-select v-model="chooseMtr" filterable placeholder="请选择" @change="mtrChange">
          <el-option v-for="item in proceMtrOptions" :key="item.mtrId" :label="item.mtrName" :value="item.mtrId">
          </el-option>
        </el-select>
        <transition name="el-fade-in-linear" v-for="(item, index) in form.proceInfos[nowProceindex].proceMtrs"
          :key="item.mtrId">
          <transition name="el-fade-in">
            <el-card
              style="position: relative;border-radius: 15px;margin-top: 5px;margin-bottom: 5px;background-image: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);"
              shadow="always">
              <div style="display: inline-block;">
                <label style="display: block;">物料编码:{{ item.mtrCode }}</label>
                <label style="display: block;">物料名称:{{ item.mtrName }}</label>
              </div>
              <div style="display: inline-block;">
                <label>数量</label>
                <el-input-number v-model="form.proceInfos[nowProceindex].proceMtrs[index].mtrQuantity"
                  controls-position="right" :min="0" size="mini"></el-input-number>
              </div>
              <div
                style="display: flex;text-align: center;position: absolute;right: 0;top: 0; height: 100%;width: 80px;align-items: center;justify-content: center;">
                <el-button id="daohuobtn" type="danger" icon="el-icon-delete" circle
                  @click="proceMtrDel(index)"></el-button>
              </div>
            </el-card>

          </transition>
        </transition>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="proMtrSetOpen = false">确 定</el-button>
        </div>
      </el-dialog>
    </transition>



    <!-- 工序设备设置对话框 -->
    <transition name="el-fade-in">
      <el-dialog title="工序设备设置" :visible.sync="proDeviceSetOpen" v-if="proDeviceSetOpen" width="500px" append-to-body>
        <label>选择设备</label>
        <el-select v-model="chooseDevice" filterable placeholder="请选择" @change="deviceChange">
          <el-option v-for="item in proceDeviceOptions" :key="item.id" :label="item.deviceName" :value="item.deviceCode">
          </el-option>
        </el-select>
        <transition name="el-fade-in-linear" v-for="(item, index) in form.proceInfos[nowProceindex].deviceInfos"
          :key="item.id">
          <transition name="el-fade-in">
            <el-card
              style="position: relative;border-radius: 15px;margin-top: 5px;margin-bottom: 5px;background-image: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);"
              shadow="always">
              <div style="display: inline-block;">
                <label style="display: block;">设备编码:{{ item.deviceCode }}</label>
                <label style="display: block;">设备名称:{{ item.deviceName }}</label>
              </div>

              <div
                style="display: flex;text-align: center;position: absolute;right: 0;top: 0; height: 100%;width: 80px;align-items: center;justify-content: center;">
                <el-button id="daohuobtn" type="danger" icon="el-icon-delete" circle
                  @click="proceDeviceDel(index)"></el-button>
              </div>
            </el-card>
          </transition>
        </transition>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="proDeviceSetOpen = false">确 定</el-button>
        </div>

      </el-dialog>
    </transition>

  </div>
</template>

<script>
import { listTec, getTec, delTec, addTec, updateTec } from "@/api/mes/tec";
import { listProce } from "@/api/mes/proce";
import draggable from 'vuedraggable';
import { listProinfo } from "@/api/mes/proinfo";
import { listMtrinfo } from "@/api/mes/mtrinfo";
import { listDevice } from "@/api/mes/device"
export default {
  name: "Tec",
  components: {
    draggable,
  },
  data() {
    return {
      nomodify: false,
      //工艺原料设置对话框
      proMtrSetOpen: false,
      //工艺设备设置对话框
      proDeviceSetOpen: false,
      //工艺设备下拉框绑定数据（仅做展示）
      chooseDevice: "",
      //工艺原料下拉框绑定数据（仅做展示）
      chooseMtr: "",
      //工艺下拉框绑定数据（仅做展示）
      chooseProce: "",
      //工艺设备下拉框数据
      proceDeviceOptions: [],
      //工艺原料下拉框数据
      proceMtrOptions: [],
      //工艺下拉框数据
      proceOptions: [],
      //产品下拉框数据
      proOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //当前点击的工序下标
      nowProceindex: "",
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品工艺表格数据
      tecList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tecCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        tecCode: [
          { required: true, message: '工艺编码不能为空', trigger: 'change' }
        ],
        proId: [
          { required: true, message: '绑定产品不能为空', trigger: 'change' }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //删除工序设备
    proceDeviceDel(index) {
      this.form.proceInfos[this.nowProceindex].deviceInfos.splice(index, 1)
    },
    //删除工序原料
    proceMtrDel(index) {
      this.form.proceInfos[this.nowProceindex].proceMtrs.splice(index, 1)
    },
    //删除工序
    proceDel(index) {
      this.form.proceInfos.splice(index, 1)
    },
    //工序设备设置
    proDeviceSet(index) {
      this.nowProceindex = index
      this.proDeviceSetOpen = true
      listDevice().then(res => {
        this.proceDeviceOptions = res.rows
      })
    },
    //工序原料设置
    proMtrSet(index) {
      this.nowProceindex = index
      this.proMtrSetOpen = true
      listMtrinfo().then(res => {
        this.proceMtrOptions = JSON.parse(JSON.stringify(res.rows).replace(/id/g, 'mtrId'))
      })
    },
    //工序设备下拉框改变
    deviceChange(option) {
      this.chooseDevice = ""
      if (this.form.proceInfos[this.nowProceindex].deviceInfos.findIndex(e => e.deviceCode == option) != -1) {
        this.$modal.msgError("无法添加重复的设备");
      } else {
        this.form.proceInfos[this.nowProceindex].deviceInfos.push(this.proceDeviceOptions.find(e => e.deviceCode == option))
      }
    },
    //工序原料下拉框改变
    mtrChange(option) {
      this.chooseMtr = ""
      if (this.form.proceInfos[this.nowProceindex].proceMtrs.findIndex(e => e.mtrId == option) != -1) {
        this.$modal.msgError("无法添加重复的物料");
      } else {
        this.form.proceInfos[this.nowProceindex].proceMtrs.push(this.proceMtrOptions.find(e => e.mtrId == option))
      }
      console.log("🚀 ~ file: index.vue:194 ~ mtrChange ~ this.form.proceInfos[this.nowProceindex].proceMtrs:", this.form.proceInfos[this.nowProceindex].proceMtrs)
    },
    //工序下拉框改变
    proceChange(option) {
      if (this.form.proceInfos.findIndex(e => e.id == option) != -1) {
        this.$modal.msgError("无法添加重复的工序");
      } else {
        let ss = this.proceOptions.find(e => e.id == option)
        ss.deviceInfos = []
        ss.proceMtrs = []
        this.form.proceInfos.push(ss)
        // this.form.proceInfos[this.nowProceindex].proceMtrs.push(this.proceMtrOptions.find(e => e.mtrId == option))
      }



      console.log("🚀 ~ file: index.vue:303 ~ proceChange ~ this.form.proceInfos:", this.form.proceInfos)
      this.chooseProce = ""
      // console.log(this.form)
    },
    /** 查询产品工艺列表 */
    getList() {
      this.loading = true;
      listTec(this.queryParams).then(response => {
        this.tecList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      //获取产品下拉框
      listProinfo().then(res => {
        this.proOptions = res.rows;
      })
      //获取工序下拉框
      listProce().then(res => {
        this.proceOptions = res.rows;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        //产品id
        proId: null,
        //工艺编码
        tecCode: null,
        //工序集合
        proceInfos: [],
        // proceId: null,

        // proceSeque: null,
        // createBy: null,
        // createTime: null,
        // updateBy: null,
        // updateTime: null,
        // remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.nomodify = false;
      this.title = "添加产品工艺";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.nomodify = true
      const id = row.id || this.ids
      getTec({ id: id }).then(response => {
        response.data.proceInfos.sort((a, b) => { return a.proceSeque - b.proceSeque })
        this.form = response.data;
        console.log("🚀 ~ file: index.vue:385 ~ getTec ~ this.form:", this.form)
        this.open = true;
        this.title = "修改产品工艺";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.proceInfos.forEach((item, index) => {
            item.proceSeque = index
          })
          console.log("🚀 ~ file: index.vue:398 ~ this.form.proceInfos.forEach ~ this.form:", this.form)
          if (this.form.id != null) {
            updateTec(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTec(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除产品工艺编号为"' + ids + '"的数据项？').then(function () {
        return delTec(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/tec/export', {
        ...this.queryParams
      }, `tec_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
#daohuobtn {
  height: 45px;
  width: 45px;
  position: relative;
  align-items: center;
  justify-content: center;
  transition: width 0.3s, height 0.3s, border-radius 0.3s;
}

#daohuobtn:hover {
  height: 100%;
  width: 100%;
  border-radius: unset;
}

#shebeibtn {
  font-size: 10px;
  font-weight: 700;
  height: 45px;
  width: 45px;
  position: relative;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  border-radius: 10px;
  border: unset;
  background-color: rgba(158, 190, 199, 0.815);
}

#shebeibtn:hover {
  height: 100%;
  width: 100%;
  border-radius: 5px;
}</style>
